package org.jks.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.FileCleanerCleanup;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileCleaningTracker;
import org.jks.constant.Constants;
import org.jks.constant.SysConfig;
import org.jks.response.model.ActionResult;
import org.jks.service.WorkService;
import org.springframework.beans.factory.annotation.Autowired;

public class UploadServlet extends HttpServlet {
	@Autowired
	WorkService workService;
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
		
		ActionResult ar = new ActionResult();
		String workName= req.getParameter("Name");
		int type = req.getParameter("type") == null ? 1 : Integer.valueOf(req.getParameter("type"));
		
		String basePath = req.getServletContext().getRealPath("/") + File.separator + SysConfig.ATTACHEMENT + File.separator + SysConfig.WORK_DIR + File.separator + "飞巡作业"; 
		String path = basePath + File.separator + workName;
		if(type == 2){
			path += File.separator + Constants.WORK_DEFECT_IMG;
		}
		else if(type == 3){
			path += File.separator + Constants.WORK_VEDIO;
		}
		
		File dir = new File(path);
		if(!dir.exists())
		{
			dir.mkdir();
		}
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		if (!isMultipart){
			System.out.println(">> This wasn't a file upload request!");
			return;
		}
		
		PrintWriter out = resp.getWriter();
		
		// create factory and file cleanup tracker
		FileCleaningTracker tracker = FileCleanerCleanup.getFileCleaningTracker(getServletContext());
		File tmpDir = new File(path);
		DiskFileItemFactory factory = new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD,  tmpDir);
		factory.setFileCleaningTracker(tracker);
		
		// save upload file to disk
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<FileItem> items = upload.parseRequest(req);
			String fileName = null;
			File savefile = null;
			for (FileItem item : items){
				if (!item.isFormField()){
					fileName = item.getName();
					savefile = new File(path + "/" + fileName);
					item.write(savefile);
					System.out.println(">> [save] " + savefile.getAbsolutePath());

					// to client info
					out.print("fileId=" + savefile.getAbsolutePath());
					out.flush();
				}
			}
			out.close();
			ar.setSuccess(true);	
			ResponseUtil.returnJson(resp, ar);
		} catch (Exception e) {
			System.out.println(">> " + e.getMessage());
			throw new IOException(e.getMessage());
		}
	}
}
